package com.it.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it.reggie.common.CustomException;
import com.it.reggie.entity.Category;
import com.it.reggie.entity.Dish;
import com.it.reggie.entity.Setmeal;
import com.it.reggie.mapper.CategoryMapper;
import com.it.reggie.service.CategoryService;
import com.it.reggie.service.DishService;
import com.it.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category>  implements CategoryService {

    //注入菜品service
    @Autowired
    private DishService dishService;
    //注入套餐service
    @Autowired
    private SetmealService setmealService;

   //根据id来删除分类，删除之前，需要进行判断
    @Override
    public void remove(Long id) {
        //构造查询条件(MyBatis-Plus库中的LambdaQueryWrapper类)
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询(查找Id等于id的Dish)
        dishLambdaQueryWrapper.eq(Dish::getCategoryId,id);
        //指定'Dish'对象的'categoryId'属性应该等于提供的'id'的值。
//要执行查询并检索匹配的菜肴，需要使用mapper类中的‘selectList’之类的方法:
//List<Dish> dishes = dishMapper.selectList(dishLambdaQueryWrapper);
        //根据select count(*) from dish where category_id = 139....,组装查询条件
        int count1 = (int) dishService.count(dishLambdaQueryWrapper);
        //查询当前分类是否关联了菜品，如果已经关联，就抛出一个业务异常
        if(count1 > 0){//说明已经关联了菜品，抛出异常
            throw new CustomException("当前分类下关联了菜品，无法删除");

        }
        //查询当前分类是否关联了/套餐，如果已经关联，就抛出一个业务异常
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据分类id进行查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        //指定'Setmeal'对象的'categoryId'属性应该等于提供的'id'的值。
//例：setmealLambdaQueryWrapper.likeRight(Setmeal::getName, "Healthy");
//查找名字以"Healthy"开头的setmeals
        int count2 = (int) setmealService.count(setmealLambdaQueryWrapper);
        if(count2 > 0){//说明已经关联了套餐，抛出异常
            throw new CustomException("当前分类下关联了套餐，无法删除");
        }

        //否则正常删除分类
        super.removeById(id);
    }
}
